package com.ckzp.jfinal.system.util;

import com.ckzp.core.ConfigUtil;
import com.ckzp.core.Results;
import com.ckzp.core.file.FileControl;
import com.ckzp.core.util.DateUtil;
import com.ckzp.core.util.StringUtil;
import com.ckzp.jfinal.system.model.SysCode;
import com.ckzp.jfinal.system.model.SysCodeColumn;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 51594 on 2021/4/9.
 */
public class SysCodeUtil {


    private boolean hasNumber = false;
    private boolean hasUpload = false;
    private boolean hasColor = false;
    private boolean hasIcon = false;
    private boolean hasDate = false;
    private boolean hasSelect = false;

    /**
     * @return
     */
    public static SysCodeUtil n() {
        return new SysCodeUtil();
    }

    /**
     * @param c_id
     * @return
     */
    public Results InitSysCodeColumn(int c_id) {
        SysCode code = SysCode.dao.findById(c_id);
        if (code != null) {
            String tablename = code.mod.getStr("table_name");
            String sql = "SELECT column_name,data_type,column_comment,column_type FROM information_schema.COLUMNS WHERE table_name = ?";
            List<SysCodeColumn> lo = SysCodeColumn.dao.find(sql, tablename);
            for (SysCodeColumn t : lo) {
                String column_name = t.getStr("column_name");
                String column_comment = t.getStr("column_comment");
                String data_type = t.getStr("data_type");
                if (column_name == null) {
                    column_name = t.getStr("COLUMN_NAME");
                    column_comment = t.getStr("COLUMN_COMMENT");
                    data_type = t.getStr("DATA_TYPE");
                }
                SysCodeColumn cnew = SysCodeColumn.dao.findFirst("select * from sys_code_column where c_id=? and cc_name=?", c_id, column_name);
                if (cnew == null) {
                    SysCodeColumn cc = new SysCodeColumn().set("cc_name", column_name)
                            .set("c_id", c_id)
                            .set("cc_name", column_name)
                            .set("cc_title", column_comment)
                            .set("cc_type", data_type);
                    if (column_name.indexOf("desc") > -1 || column_name.indexOf("test") > -1) {
                        cc.set("f_more", 1);//多行
                    }
                    if (column_name.indexOf("img") > -1) {
                        cc.set("f_img", 1);//图片
                    }

                    if (column_name.indexOf("date") > -1 || column_name.indexOf("time") > -1) {
                        cc.set("f_date", 1);//日期选择
                    }
                    cc.save();
                }
            }
            return Results.n(0, "初始化成功");
        } else {
            return Results.n(9, "CID不存在[" + c_id + "]");
        }
    }


    public String getCodeConfig(SysCode code) {
        String tablename = code.mod.getStr("table_name");
        String modelname = code.mod.getStr("model_name");
        String modelkey = code.mod.getStr("model_key");
        StringBuffer sb = new StringBuffer();
        //sb.append("//Config.java 数据库映射\n");
        sb.append("arp.addMapping(\"" + tablename + "\", \"" + modelkey + "\", " + modelname + ".class);\r\n");
        return sb.toString();
    }


    public String getCodeRoute(SysCode code) {
        String tablename = code.mod.getStr("table_name");
        String modelname = code.mod.getStr("model_name");
        String model_path = code.mod.getStr("model_path");
        StringBuffer sb = new StringBuffer();
        //sb.append("//Config.java 数据库映射\n");
        sb.append("add(ADMIN_PATH + \"/" + model_path + "\", " + modelname + "Controller.class, \"/" + model_path + "\");\r\n");
        return sb.toString();
    }

    /**
     * 生成Model文件
     *
     * @param code
     * @return
     */
    public String getCodeModel(SysCode code) {
        String tablename = code.mod.getStr("table_name");
        String modelname = code.mod.getStr("model_name");
        String packagename = code.mod.getStr("package_name");
        String data = new StringBuffer(readDemoFile("Demo.java.temp")).toString();
        data = StringUtil.replace(data, "[package]", packagename);
        data = StringUtil.replace(data, "[model]", modelname);
        data = StringUtil.replace(data, "[tablename]", tablename);
        data = StringUtil.replace(data, "[date]", DateUtil.getDateTime());
        return data;
    }


    /**
     * 生成Model文件
     *
     * @param code
     * @return
     */
    public String getCodeController(SysCode code) {
        String tablename = code.mod.getStr("table_name");
        String table_title = code.mod.getStr("table_title");
        String pagename = StringUtil.replace(table_title, "表", "");
        String modelname = code.mod.getStr("model_name");
        String packagename = code.mod.getStr("package_name");
        String modelkey = code.mod.getStr("model_key");
        String modelsname = code.mod.getStr("model_sname");
        String table_role = code.mod.getStr("table_role");
        String tree_key = code.mod.getStr("tree_key", "");
        int list_tree = code.mod.getInt("list_tree", 0);
        int form_v_api = code.mod.getInt("form_v_api");
        String columns = "";
        List<SysCodeColumn> columnlist = getCodeColumn(code);
        String data = new StringBuffer(readDemoFile("DemoController.java.temp")).toString();
        data = StringUtil.replace(data, "[pagename]", pagename);
        data = StringUtil.replace(data, "[role]", table_role);
        data = StringUtil.replace(data, "[package]", packagename);
        data = StringUtil.replace(data, "[model]", modelname);
        data = StringUtil.replace(data, "[modelkey]", modelkey);
        data = StringUtil.replace(data, "[tablename]", tablename);
        data = StringUtil.replace(data, "[date]", DateUtil.getDateTime());
        data = StringUtil.replace(data, "[columns]", columns);
        data = StringUtil.replace(data, "[editcolumn]", getCodeEditColumnCode(columnlist));
        data = StringUtil.replace(data, "[setcolumns]", getCodeModifyColumnCode(code, columnlist));
        data = StringUtil.replace(data, "[dotagmethod]", getControllerTagMethod(code, columnlist));
        data = StringUtil.replace(data, "[sqlsearch]", getControllerSqlSearch(columnlist));
        data = StringUtil.replace(data, "[listcolumnput]", getListColumnPut(columnlist));
        data = StringUtil.replace(data, "[modelsname]", modelsname);
        if (tree_key.length() > 0) {
            data = StringUtil.replace(data, "[addfd]", "setAttr(\"" + modelsname + "\", new " + modelname + "().put(\"" + tree_key + "\",getPara(\"" + tree_key + "\")));");
            data = StringUtil.replace(data, "[treekey]", "ps.search(\"" + tree_key + "\", getPara(\"" + tree_key + "\", \"0\"));");
        } else {
            data = StringUtil.replace(data, "[addfd]", "setAttr(\"" + modelsname + "\", new " + modelname + "());");
            data = StringUtil.replace(data, "[treekey]", "");
        }
        if (list_tree == list_tree) {
            data = StringUtil.replace(data, "[treelist]", getControllerTreeList());
        } else {
            data = StringUtil.replace(data, "[treelist]", "");
        }
        data = StringUtil.replace(data, "[addformdata]", getAddFormData(code, columnlist));
        data = StringUtil.replace(data, "[editformdata]", getEditFormData(code, columnlist));
        if (form_v_api == 1) {
            data = StringUtil.replace(data, "[validator]", "    @Before(" + modelname + "Validator.class)");
        } else {
            data = StringUtil.replace(data, "[validator]", "");
        }

        return data;
    }


    public String getAddFormData(SysCode code, List<SysCodeColumn> slist) {
        String tree_key = code.mod.getStr("tree_key", "");
        String modelsname = code.mod.getStr("model_sname");
        String modelname = code.mod.getStr("model_name");
        StringBuffer sb = new StringBuffer();
        if (tree_key.length() > 0) {
            sb.append("setAttr(\"" + modelsname + "\", new " + modelname + "().put(\"" + tree_key + "\",getPara(\"" + tree_key + "\")));");
        } else {
            sb.append("setAttr(\"" + modelsname + "\", new " + modelname + "());");
        }
        for (SysCodeColumn c : slist) {
            String cname = c.mod.getStr("cc_name", "");
            if (c.mod.getInt("f_select") == 1) {
                sb.append("FormSelect " + cname + "_s = SysDataCache.getFormSelect(\"\").setCanNull(true).setDefaultString(\"全部\");\n");
                sb.append("fd.addSelect(\"" + cname + "_html\"," + cname + "_s.showHtml(\"\"));");
            }
        }
        return sb.toString();
    }


    public String getEditFormData(SysCode code, List<SysCodeColumn> slist) {
        String tree_key = code.mod.getStr("tree_key", "");
        String modelsname = code.mod.getStr("model_sname");
        String modelname = code.mod.getStr("model_name");
        StringBuffer sb = new StringBuffer();
        if (tree_key.length() > 0) {
            sb.append("setAttr(\"" + modelsname + "\", new " + modelname + "().put(\"" + tree_key + "\",getPara(\"" + tree_key + "\")));");
        } else {
            sb.append("setAttr(\"" + modelsname + "\", new " + modelname + "());");
        }
        for (SysCodeColumn c : slist) {
            String cname = c.mod.getStr("cc_name", "");
            if (c.mod.getInt("f_select") == 1) {
                sb.append("FormSelect " + cname + "_s = SysDataCache.getFormSelect(\"\").setDefaultString(\"全部\");\n");
                sb.append("fd.addSelect(\"" + cname + "_html\"," + cname + "_s.showHtml(o.mod.getStr(\"" + cname + "\")));");
            }
        }
        return sb.toString();
    }


    /**
     * 树表
     *
     * @return
     */
    public String getControllerTreeList() {
        return "        TreeNode tree = TreeNode.newNode(\"page1\").setTitle(\"测试分类\").setSpread(true).setTurn(false);\n" +
                "        tree = SysTypeCache.n().getTypeDetailTree(tree, \"test_type\");\n" +
                "        fd.addData(\"tree\", toJsonStr(TreeNode.newNodeList(tree)));\n" +
                "        fd.addData(\"def_id\", tree.getDatas().get(\"def_id\"));\n" +
                "        fd.addData(\"def_title\", tree.getDatas().get(\"def_title\"));\n";
    }

    /**
     * 反回搜索条件
     *
     * @return
     */
    public String getControllerSqlSearch(List<SysCodeColumn> cl) {
        List<SysCodeColumn> slist = getSearchList(cl);
        StringBuffer sb = new StringBuffer();
        for (SysCodeColumn c : slist) {
            String cname = c.mod.getStr("cc_name", "");
            String cc_type = "string";
            if ("int".equals(c.mod.getStr("cc_type"))) cc_type = "int";
            sb.append("        sql = addSearch(sql, \"" + cname + "\", \"=\", \"" + cc_type + "\", getPara(\"s[" + cname + "]\"));\n");
        }
        return sb.toString();
    }

    public String getCodeEditColumnCode(List<SysCodeColumn> cl) {
        StringBuffer sb = new StringBuffer();
        for (SysCodeColumn c : cl) {
            int f_img = c.mod.getInt("f_img", 0);
            int f_date = c.mod.getInt("f_date", 0);
            String cname = c.mod.getStr("cc_name", "");
            if (f_img == 1) {
                sb.append("o.put(\"" + cname + "_view\", UpImage.TransUrl(o.mod.getStr(\"" + cname + "\", \"\")));\n");
            } else if (f_date == 1) {
                sb.append("o.put(\"" + cname + "_str\", DateUtil.getDateTime(o.mod.getDate(\"" + cname + "\")));\n");
            }
        }
        return sb.toString();
    }

    public String getControllerTagMethod(SysCode code, List<SysCodeColumn> cl) {
        String codes = "";
        String modelname = code.mod.getStr("model_name");
        String modelkey = code.mod.getStr("model_key");
        for (SysCodeColumn cc : cl) {
            int is_tag = cc.mod.getInt("is_tag", 0);
            String columns = cc.mod.getStr("cc_name", "");
            if (is_tag == 1) {
                codes += "/**\n" +
                        "     * TAG\n" +
                        "     */\n" +
                        "    @Roles(roles = \"login\")\n" +
                        "    public void Lock" + columns.toUpperCase() + "Api() {\n" +
                        "        renderJson(DoBasePub(" + modelname + ".dao, getParaStr(\"" + modelkey + "\", \"\"), \"" + columns + "\", \"\"));\n" +
                        "    }";
            }
        }
        return codes;
    }

    public String getListFieldArray(SysCode code, List<SysCodeColumn> cl) {

        String codes = "";
        int listtool = code.mod.getInt("list_tool", 0);

        String modelname = code.mod.getStr("model_name");
        String modelkey = code.mod.getStr("model_key");
        for (SysCodeColumn cc : cl) {
            if (cc.mod.getInt("t_show", 0) == 1) {
                int is_key = cc.mod.getInt("is_key", 0);
                int t_edit = cc.mod.getInt("t_edit", 0);

                int t_width = cc.mod.getInt("t_width", 0);
                int t_checkbox = cc.mod.getInt("t_checkbox", 0);
                int t_select = cc.mod.getInt("t_select", 0);
                int t_switch = cc.mod.getInt("t_switch", 0);
                int t_center = cc.mod.getInt("t_center", 0);
                int t_img = cc.mod.getInt("t_img", 0);
                int is_date = cc.mod.getInt("is_date", 0);
                String columns = cc.mod.getStr("cc_name", "");
                String cc_title = cc.mod.getStr("cc_title", "");
                if (is_date > 0) columns = columns + "_str";
                codes += ", {field: '" + columns + "', title: '" + cc_title + "'";
                if (t_width > 0) codes += ",width: " + t_width;
                if (t_edit == 1) codes += ",edit: 'text'";
                if (t_center == 1) codes += ",align: 'center'";
                if (is_key == 1) codes += ",sort: true";
                if (t_img == 1) codes += ",image: {show: true, url: '" + columns.toLowerCase() + "_view', style: 'width:40px'}";
                if (t_checkbox + t_select + t_switch > 0) codes += ",templet: '#temp_" + columns.toLowerCase() + "'";
                codes += "}\n";
            }
        }
        if (listtool == 1) {
            codes += ", {fixed: 'right', title: '操作', toolbar: '#table_bar_tool', width: 200, align: 'center'}";
        }
        return codes;
    }

    public String getListTemplet(List<SysCodeColumn> clist) {
        StringBuffer sb = new StringBuffer();
        for (SysCodeColumn cc : clist) {
            String columns = cc.mod.getStr("cc_name", "");
            String cc_title = cc.mod.getStr("cc_title", "");
            int t_checkbox = cc.mod.getInt("t_checkbox", 0);
            int t_select = cc.mod.getInt("t_select", 0);
            int t_switch = cc.mod.getInt("t_switch", 0);
            if (t_switch == 1) {
                sb.append("\n                    <script type=\"text/html\" id=\"temp_" + columns + "\">\n" +
                        "                        <input type=\"checkbox\" lay-skin=\"switch\" field=\"" + columns + "\" msg=\"" + cc_title + "\" value=\"{{d.[modelkey]}}\" lay-text=\"ON|OFF\" lay-filter=\"ChangeTag\" {{ d." + columns + " ? 'checked' : '' }}>\n" +
                        "                    </script>");
            } else if (t_checkbox == 1) {
                sb.append("\n                    <script type=\"text/html\" id=\"temp_" + columns + "\">\n" +
                        "                        <input type=\"checkbox\" lay-skin=\"primary\" field=\"" + columns + "\" msg=\"设置" + cc_title + "\" value=\"{{d.[modelkey]}}\" lay-filter=\"ChangeTag\" {{ d." + columns + " ? 'checked' : '' }}>\n" +
                        "                    </script>");
            } else if (t_select == 1) {
                sb.append("\n                    <script type=\"text/html\" id=\"temp_" + columns + "\">\n" +
                        "                        <input type=\"checkbox\" field=\"" + columns + "\" msg=\"" + cc_title + "\" value=\"{{d.[modelkey]}}\" title=\"允许\" lay-filter=\"ChangeTag\" {{ d." + columns + " ? 'checked' : '' }}>\n" +
                        "                    </script>");
            }
        }
        return sb.toString();
    }


    public String getListSearch(List<SysCodeColumn> clist) {
        StringBuffer sb = new StringBuffer();
        for (SysCodeColumn cc : clist) {
            String columns = cc.mod.getStr("cc_name", "");
            String cc_title = cc.mod.getStr("cc_title", "");
            int t_search = cc.mod.getInt("t_search", 0);
            int t_select = cc.mod.getInt("t_select", 0);
            int t_switch = cc.mod.getInt("t_switch", 0);
            if (t_search == 1) {
                sb.append("<input type=\"text\" id=\"" + columns + "\" placeholder=\"" + cc_title + "\"class=\"table-search-text width80\"/>\n");
            }
        }
        return sb.toString();
    }

    public static String getListColumnPut(List<SysCodeColumn> clist) {
        StringBuffer sb = new StringBuffer();
        int k = 0;
        for (SysCodeColumn cc : clist) {
            String columns = cc.mod.getStr("cc_name", "");
            String cc_title = cc.mod.getStr("cc_title", "");
            int t_search = cc.mod.getInt("t_search", 0);
            int t_select = cc.mod.getInt("t_select", 0);
            int t_img = cc.mod.getInt("t_img", 0);
            int is_date = cc.mod.getInt("is_date", 0);
            if (t_img == 1) {
                if (k > 0) sb.append("\n");
                sb.append("[modelsname].put(\"" + columns + "_view\", UpImage.TransUrl([modelsname].mod.getStr(\"" + columns + "\", \"\")));");
                k = 1;
            } else if (is_date == 1) {
                if (k > 0) sb.append("\n");
                sb.append("[modelsname].put(\"" + columns + "_str\", DateUtil.getDateTime([modelsname].mod.getDate(\"" + columns + "\")));");
                k = 1;
            }
        }
        return sb.toString();
    }


    public String getListSearchMoreDiv(List<SysCodeColumn> clist) {
        StringBuffer sb = new StringBuffer();
        sb.append("<button class=\"layui-btn btn-search-adv layui-btn-sm\" lay-event=\"DoSearchMore\">高级搜索</button>\n");
        int k = 0, count = 0;
        for (SysCodeColumn cc : clist) {
            count++;
        }
        sb.append("");
        if (count == 0) return "";

        return sb.toString();
    }


    public String getListSearchMore(List<SysCodeColumn> clist) {
        StringBuffer sb = new StringBuffer();
        sb.append("                    <script type=\"text/template\" id=\"SearchMoreTemp\">\n" +
                "                        <form class=\"layui-form\">\n");
        int k = 0, count = 0;
        for (SysCodeColumn cc : clist) {
            String columns = cc.mod.getStr("cc_name", "");
            String cc_title = cc.mod.getStr("cc_title", "");
            int t_searchs = cc.mod.getInt("t_searchs", 0);
            int t_select = cc.mod.getInt("t_select", 0);
            int t_switch = cc.mod.getInt("t_switch", 0);
            if (t_searchs == 1) {
                sb.append("<div class=\"margin-10\"><input type=\"text\" id=\"" + columns + "\" placeholder=\"请输入" + cc_title + "\" autocomplete=\"off\" class=\"layui-input\"></div>");
                k = 1;
                count++;
            }
        }
        sb.append("                  </form>\n" +
                "                    </script>");
        if (count == 0) return "";

        return sb.toString();
    }

    /**
     * 搜索
     *
     * @param clist
     * @return
     */
    public static String getListSearchMoreJs(List<SysCodeColumn> clist) {
        StringBuffer sb = new StringBuffer();
        int k = 0, count = 0;
        sb.append("        drawer1 = layui.drawer.render({\n" +
                "            title: '<b><i class=\"layui-icon layui-icon-app\"></i> 高级搜索</b>', offset: 'r', width: \"300px\", content: SearchMoreTemp.innerHTML,\n" +
                "            btn: ['<i class=\"layui-icon\">&#xe615;</i>搜索', '重置'],\n" +
                "            success: function (layero, index) {\n" +
                "                layui.form.render('select');\n" +
                "            },\n" +
                "            btn1: function (index, layero) {\n" +
                "                tableindex.reload({\n" +
                "                    where: {[treekey]:$(\"#[treekey]\").val(),s: {\n");
        for (SysCodeColumn cc : clist) {
            int t_search = cc.mod.getInt("t_search", 0);
            int t_searchs = cc.mod.getInt("t_searchs", 0);
            String columns = cc.mod.getStr("cc_name", "");
            if (t_search + t_searchs > 0) {
                if (k > 0) sb.append(",");
                if (t_search == 1) sb.append(columns + ": $(layero).find(\"#" + columns + "\").val()\n");
                if (t_searchs == 1) sb.append(columns + ": $(\"#" + columns + "\").val()\n");
                count++;
                k = 1;
            }
        }
        sb.append(
                "                        }\n" +
                        "                    }\n" +
                        "                    , page: {curr: 1}\n" +
                        "                });\n" +
                        "            },\n" +
                        "            btn2: function (index, layero) {\n" +
                        "                $(layero).find(\"form\")[0].reset();//重置\n" +
                        "                return false;\n" +
                        "            }\n" +
                        "        });\n");
        if (count == 0) return "";

        return sb.toString();
    }

    /**
     * 导航
     *
     * @return
     */
    public static String getListToolBar() {
        StringBuffer sb = new StringBuffer();
        sb.append("                    <script type=\"text/html\" id=\"table_bar_tool\">\n" +
                "                        <a class=\"layui-btn layui-btn-normal layui-btn-xs\" lay-event=\"Edit[model]\">修改</a>\n" +
                "                    </script>");
        return sb.toString();
    }


    /**
     * 导航
     *
     * @return
     */
    public String getListToolJs() {
        return new StringBuffer(readDemoFile("tmp_list_tool.html")).toString();
    }

    public static String getListSearchJs(List<SysCodeColumn> clist) {
        StringBuffer sb = new StringBuffer();
        sb.append("s: {");
        int k = 0, count = 0;
        for (SysCodeColumn cc : clist) {
            String columns = cc.mod.getStr("cc_name", "");
            String cc_title = cc.mod.getStr("cc_title", "");
            int t_search = cc.mod.getInt("t_search", 0);
            if (t_search == 1) {
                if (k > 0) sb.append(",");
                sb.append(columns + ": $(\"#" + columns + "\").val()");
                k = 1;
                count++;
            }
        }
        sb.append("}");
        if (count == 0) return "";
        return sb.toString();
    }
    //

    /**
     * 生成Model文件
     *
     * @param code
     * @return
     */
    public String getCodeList(SysCode code) {
        String tablename = code.mod.getStr("table_name");
        String table_title = code.mod.getStr("table_title");
        String pagename = StringUtil.replace(table_title, "表", "");
        String modelname = code.mod.getStr("model_name");
        String packagename = code.mod.getStr("package_name");
        String modelpath = code.mod.getStr("model_path");
        String modelkey = code.mod.getStr("model_key");
        String modelsname = code.mod.getStr("model_sname");
        String tree_key = code.mod.getStr("tree_key");
        int listtree = code.mod.getInt("list_tree", 0);
        int listtool = code.mod.getInt("list_tool", 0);
        int searchmore = code.mod.getInt("list_searchmore", 0);
        String columns = "";
        String data = "";
        if (listtree == 1) {
            data = new StringBuffer(readDemoFile("DemoTreeList.html")).toString();
        } else {
            data = new StringBuffer(readDemoFile("DemoList.html")).toString();
        }
        List<SysCodeColumn> columnlist = getCodeColumn(code);


        if (searchmore == 1) {
            data = StringUtil.replace(data, "[searchmore]", getListSearchMore(columnlist));
            data = StringUtil.replace(data, "[searchmorejs]", getListSearchMoreJs(columnlist));
            data = StringUtil.replace(data, "[searchmorediv]", getListSearchMoreDiv(columnlist));
        } else {
            data = StringUtil.replace(data, "[searchmore]", "");
            data = StringUtil.replace(data, "[searchmorejs]", "");
            data = StringUtil.replace(data, "[searchmorediv]", "");
        }

        if (listtool == 1) {
            data = StringUtil.replace(data, "[tabletooljs]", getListToolJs());
            data = StringUtil.replace(data, "[tabletoolbar]", getListToolBar());
        } else {
            data = StringUtil.replace(data, "[tabletooljs]", "");
            data = StringUtil.replace(data, "[tabletoolbar]", "");
        }

        data = StringUtil.replace(data, "[path]", modelpath);
        data = StringUtil.replace(data, "[package]", packagename);
        data = StringUtil.replace(data, "[tablename]", tablename);
        data = StringUtil.replace(data, "[date]", DateUtil.getDateTime());
        data = StringUtil.replace(data, "[columns]", getListFieldArray(code, columnlist));
        data = StringUtil.replace(data, "[templet]", getListTemplet(columnlist));
        data = StringUtil.replace(data, "[searchdiv]", getListSearch(columnlist));
        data = StringUtil.replace(data, "[searchjs]", getListSearchJs(columnlist));

        data = StringUtil.replace(data, "[model]", modelname);
        data = StringUtil.replace(data, "[modelkey]", modelkey);
        data = StringUtil.replace(data, "[pagename]", pagename);
        data = StringUtil.replace(data, "[modelsname]", modelsname);
        data = StringUtil.replace(data, "[treekey]", tree_key);

        return data;
    }

    /**
     * 生成Model文件
     *
     * @param code
     * @return
     */
    public String getCodeModify(SysCode code) {
        String tablename = code.mod.getStr("table_name");
        String modelname = code.mod.getStr("model_name");
        String packagename = code.mod.getStr("package_name");
        String modelkey = code.mod.getStr("model_key");
        String modelsname = code.mod.getStr("model_sname");
        List clist = getCodeColumn(code);
        int form_v_js = code.mod.getInt("form_v_js", 0);
        String columns = getCodeModifyColumn(clist, form_v_js);
        String data = new StringBuffer(readDemoFile("ModifyDemo.html")).toString();
        data = StringUtil.replace(data, "[package]", packagename);
        data = StringUtil.replace(data, "[modelkey]", modelkey);
        data = StringUtil.replace(data, "[tablename]", tablename);
        data = StringUtil.replace(data, "[date]", DateUtil.getDateTime());
        data = StringUtil.replace(data, "[columns]", columns);
        data = StringUtil.replace(data, "[modifyjs]", getModifyJsString(clist));
        //data = StringUtil.replace(data, "[uploadimg]", getModifyJsUpload(clist));
        data = StringUtil.replace(data, "[hidden]", getModifyHidden(clist));
        data = StringUtil.replace(data, "[model]", modelname);
        data = StringUtil.replace(data, "[modelsname]", modelsname);
        return data;
    }


    /**
     * 生成Model文件
     *
     * @param code
     * @return
     */
    public String getCodeValidate(SysCode code) {
        String modelname = code.mod.getStr("model_name");
        String packagename = code.mod.getStr("package_name");
        int form_v_api = code.mod.getInt("form_v_api");
        List clist = getCodeColumn(code);
        String validate = getCodeValidateColumn(clist, form_v_api == 1);
        String data = new StringBuffer(readDemoFile("DemoValidate.java.temp")).toString();
        data = StringUtil.replace(data, "[package]", packagename);
        data = StringUtil.replace(data, "[model]", modelname);
        data = StringUtil.replace(data, "[validate]", validate);
        return data;
    }

    public String getModifyJsUpload(List<SysCodeColumn> clist) {
        int count = 0;
        StringBuffer sb = new StringBuffer();
        sb.append("layui.use('upload', function () {\n");
        for (SysCodeColumn code : clist) {
            if (code.mod.getInt("is_img", 0) == 1) {
                String cname = code.mod.getStr("cc_name");
                sb.append("        layui.upload.render({\n" +
                        "            elem: '#imagebtn_" + cname + "', url: 'UploadImages', size: 300, accept: 'image', exts: 'jpg|gif|png'\n" +
                        "            , done: function (res) {\n" +
                        "                if (res.code == 0) {\n" +
                        "                    $('#image" + cname + "').attr('src', res.object.view_path);\n" +
                        "                    $('#" + cname + "').val(res.object.save_path);\n" +
                        "                    return layer.msg('上传成功');\n" +
                        "                } else {\n" +
                        "                    return layer.msg('上传失败');\n" +
                        "                }\n" +
                        "            }\n" +
                        "        });\n");
                count++;
            }
        }
        sb.append("    });");
        if (count == 0) return "";
        return sb.toString();
    }

    /**
     * 日期
     *
     * @param clist
     * @return
     */
    public String getModifyJsString(List<SysCodeColumn> clist) {
        int count = 0;
        StringBuffer sb = new StringBuffer();
        if (hasColor || hasDate || hasIcon || hasNumber) {
            sb.append("layui.use(['form'");
            if (hasDate) sb.append(",'laydate'");
            if (hasColor) sb.append(",'myColor'");
            if (hasIcon) sb.append(",'myIcon'");
            if (hasNumber) sb.append(",'myNumber'");
            if (hasUpload) sb.append(",'myUpload'");
            sb.append("], function () {\n");
            for (SysCodeColumn code : clist) {
                if (code.mod.getInt("f_date", 0) == 1) {
                    count++;
                    String cname = code.mod.getStr("cc_name");
                    sb.append("        layui.laydate.render({elem: '#" + cname + "', type: 'datetime', format: 'yyyy-MM-dd HH:mm:ss'});\n");
                }
            }
            if (hasNumber) sb.append("layui.myNumber.render({readonly: true, min: 1, max: 5, step: 2});\n");
            if (hasUpload) sb.append("layui.myUpload.render({btn_class: \"layui-btn-sm btn-change-13\", btn_txt: '上传'});\n");
            if (hasColor) sb.append("layui.myColor.render({});\n");
            if (hasIcon) sb.append("layui.myIcon.render({});\n");
            sb.append("    });");
        }
        if (count == 0) return "";
        return sb.toString();
    }

    public String getModifyHidden(List<SysCodeColumn> clist) {
        int count = 0;
        StringBuffer sb = new StringBuffer();
        for (SysCodeColumn code : clist) {
            if (code.mod.getInt("f_hidden", 0) == 1) {
                count++;
                String cname = code.mod.getStr("cc_name");
                sb.append("        <input type=\"hidden\" id=\"" + cname + "\" name=\"" + cname + "\" value=\"#([modelsname]." + cname + ")\">\n");
            }
        }
        if (count == 0) return "";
        return sb.toString();
    }

    /**
     * 按行取字段
     *
     * @param clist
     * @param rows
     * @return
     */
    public List getRowColumn(List<SysCodeColumn> clist, int rows) {
        List<SysCodeColumn> relist = new ArrayList();
        for (SysCodeColumn cc : clist) {
            int f_show = cc.mod.getInt("f_show", 0);
            if (f_show == 1 && rows == cc.mod.getInt("f_sindex")) {
                relist.add(cc);
            }
        }
        return relist;
    }

    /**
     * 生成Model文件
     *
     * @param clist
     * @return
     */
    public String getCodeModifyColumn(List<SysCodeColumn> clist, int form_v_js) {
        String columns = "";
        StringBuffer sb = new StringBuffer();
        for (int row = 0; row < 20; row++) {
            List<SysCodeColumn> rowlist = getRowColumn(clist, row);
            int size = rowlist.size();
            if (size > 0) {
                sb.append("<div class=\"layui-row\">\n" +
                        "    <div class=\"layui-col-md12\">\n" +
                        "        <div class=\"layui-form-item\">\n");
                for (int k = 0; k < rowlist.size(); k++) {
                    SysCodeColumn cc = (SysCodeColumn) rowlist.get(k);
                    int f_show = cc.mod.getInt("f_show", 0);
                    int f_key = cc.mod.getInt("f_key", 0);
                    int f_auto = cc.mod.getInt("f_auto", 0);
                    int f_readonly = cc.mod.getInt("f_readonly", 0);
                    int f_img = cc.mod.getInt("f_img", 0);
                    int f_more = cc.mod.getInt("f_more", 0);
                    int f_date = cc.mod.getInt("f_date", 0);
                    int f_number = cc.mod.getInt("f_number", 0);
                    int f_color = cc.mod.getInt("f_color", 0);
                    int f_icon = cc.mod.getInt("f_icon", 0);
                    int f_select = cc.mod.getInt("f_select", 0);
                    int f_switch = cc.mod.getInt("f_switch", 0);
                    String cc_name = cc.mod.getStr("cc_name");
                    String cc_type = cc.mod.getStr("cc_type");
                    String cctitle = cc.mod.getStr("cc_title");
                    int f_width = cc.mod.getInt("f_width", 0);
                    String layrequired = "";
                    if (form_v_js == 1 && cc.mod.getInt("f_vnull", 0) == 1) layrequired = " lay-verify=\"required\"";
                    if (form_v_js == 1 && cc.mod.getInt("f_vnumber", 0) == 1) layrequired = " lay-verify=\"number\"";
                    if (form_v_js == 1 && cc.mod.getInt("f_vemail", 0) == 1) layrequired = " lay-verify=\"email\"";
                    if (form_v_js == 1 && cc.mod.getInt("f_vdate", 0) == 1) layrequired = " lay-verify=\"date\"";
                    if (f_show == 1) {
                        if (f_img == 1) {
                            hasUpload = true;
                            if (k == 0) sb.append("            <label class=\"layui-form-" + (k == 0 ? "label" : "mid") + "\">" + cctitle + "</label>\n");
                            sb.append("<div class=\"layui-input-inline\" style=\"width:" + (f_width > 0 ? f_width : 200) + "px\">\n" +
                                    "                        <input type=\"text\" lay-skin=\"myupload\" class=\"layui-hide\"" +
                                    " width=\"100\" height=\"60\"  btn_txt=\"上传\" btn_class=\"layui-btn-xs btn-change-8\" \n" +
                                    "                               name=\"" + cc_name + "\" view_path=\"#([modelsname]." + cc_name + "_view)\" value=\"#([modelsname]." + cc_name + ")\"/>\n" +
                                    "                    </div>\n");
                        } else if (f_more == 1) {
                            sb.append("            <label class=\"layui-form-" + (k == 0 ? "label" : "mid") + "\">" + cctitle + "</label>\n" +
                                    "\n" +
                                    "            <div class=\"layui-input-" + (size == 1 ? "block" : "inline") + "\" " + (f_width > 0 ? "style=\"width:" + f_width + "px\"" : "") + ">\n" +
                                    "                        <textarea name=\"" + cc_name + "\" placeholder=\"请输入" + cctitle + "\" class=\"layui-textarea\" style=\"height:" + (f_width > 0 ? f_width : 60) + "px\">#([modelsname]." + cc_name + ")</textarea>\n" +
                                    "                    </div>");
                        } else if (f_key == 1) {
                            sb.append("            <label class=\"layui-form-" + (k == 0 ? "label" : "mid") + "\">" + cctitle + "</label>\n" +
                                    "\n" +
                                    "            <div class=\"layui-input-" + (size == 1 ? "block" : "inline") + "\" " + (f_width > 0 ? "style=\"width:" + f_width + "px\"" : "") + ">\n" +
                                    "                        <input type=\"text\" readonly name=\"" + cc_name + "\" placeholder=\"自动生成\" value=\"#([modelsname]." + cc_name + ")\" class=\"layui-input input-readonly\">\n" +
                                    "                    </div>");
                        } else if (f_date == 1) {
                            hasDate = true;
                            sb.append("            <label class=\"layui-form-" + (k == 0 ? "label" : "mid") + "\">" + cctitle + "</label>\n" +
                                    "\n" +
                                    "            <div class=\"layui-input-" + (size == 1 ? "block" : "inline") + "\" " + (f_width > 0 ? "style=\"width:" + f_width + "px\"" : "") + ">\n" +
                                    "                <input type=\"text\" id=\"" + cc_name + "\" name=\"" + cc_name + "\" autocomplete=\"off\" placeholder=\"请选择" + cctitle + "\"\n" +
                                    "                       value=\"#([modelsname]." + cc_name + "_str)\" class=\"layui-input\">\n" +
                                    "            </div>\n");
                        } else if (f_number == 1) {
                            hasNumber = true;
                            sb.append("            <label class=\"layui-form-" + (k == 0 ? "label" : "mid") + "\">" + cctitle + "</label>\n" +
                                    "\n" +
                                    "            <div class=\"layui-input-" + (size == 1 ? "block" : "inline") + "\" " + (f_width > 0 ? "style=\"width:" + f_width + "px\"" : "") + ">\n" +
                                    "                <input type=\"text\" class=\"layui-hide\" lay-skin=\"mynumber\" autocomplete=\"off\" value=\"#([modelsname]." + cc_name + ")\" step=\"1\" name=\"" + cc_name + "\">\n" +
                                    "            </div>\n");
                        } else if (f_color == 1) {
                            hasColor = true;
                            sb.append("            <label class=\"layui-form-" + (k == 0 ? "label" : "mid") + "\">" + cctitle + "</label>\n" +
                                    "\n" +
                                    "            <div class=\"layui-input-" + (size == 1 ? "block" : "inline") + "\" " + (f_width > 0 ? "style=\"width:" + f_width + "px\"" : "") + ">\n" +
                                    "                <input type=\"text\" class=\"layui-hide\" lay-skin=\"mycolor\"  value=\"#([modelsname]." + cc_name + ")\" name=\"" + cc_name + "\">\n" +
                                    "            </div>\n");
                        } else if (f_icon == 1) {
                            hasIcon = true;
                            sb.append("            <label class=\"layui-form-" + (k == 0 ? "label" : "mid") + "\">" + cctitle + "</label>\n" +
                                    "\n" +
                                    "            <div class=\"layui-input-" + (size == 1 ? "block" : "inline") + "\" " + (f_width > 0 ? "style=\"width:" + f_width + "px\"" : "") + ">\n" +
                                    "                <input type=\"text\" class=\"layui-hide\" lay-skin=\"myicon\"  value=\"#([modelsname]." + cc_name + ")\" name=\"" + cc_name + "\">\n" +
                                    "            </div>\n");
                        } else if (f_select == 1) {
                            sb.append("            <label class=\"layui-form-" + (k == 0 ? "label" : "mid") + "\">" + cctitle + "</label>\n" +
                                    "\n" +
                                    "            <div class=\"layui-input-" + (size == 1 ? "block" : "inline") + "\" " + (f_width > 0 ? "style=\"width:" + f_width + "px\"" : "") + ">\n" +
                                    "                 #(form.select." + cc_name + "_html??)\n" +
                                    "            </div>\n");
                        } else if (f_switch == 1) {
                            sb.append("           <label class=\"layui-form-" + (k == 0 ? "label" : "mid") + "\">" + cctitle + "</label>\n" +
                                    "\n" +
                                    "            <div class=\"layui-input-" + (size == 1 ? "block" : "inline") + "\" " + (f_width > 0 ? "style=\"width:" + f_width + "px\"" : "") + ">\n" +
                                    "                <input type=\"checkbox\" lay-skin=\"switch\" name=\"" + cc_name + "\" value=\"1\" lay-text=\"ON|OFF\" #([modelsname]." + cc_name + "==1?'checked':'')>\n" +
                                    "            </div>\n");
                        } else {
                            sb.append("            <label class=\"layui-form-" + (k == 0 ? "label" : "mid") + "\">" + cctitle + "</label>\n" +
                                    "\n" +
                                    "            <div class=\"layui-input-" + (size == 1 ? "block" : "inline") + "\" " + (f_width > 0 ? "style=\"width:" + f_width + "px\"" : "") + ">\n" +
                                    "                <input type=\"text\" id=\"" + cc_name + "\" name=\"" + cc_name + "\" " + (f_readonly == 1 ? "readonly" : "") + " placeholder=\"" + (f_auto == 1 ? "自动生成" : "请输入" + cctitle) + "\"\n" +
                                    "                       value=\"#([modelsname]." + cc_name + ")\" class=\"layui-input " + (f_readonly == 1 ? "input-readonly" : "") + "\">\n" +
                                    "            </div>");
                        }
                    }
                }
                sb.append("        </div>\n" +
                        "    </div>\n" +
                        "</div>");
            }
        }
        return sb.toString();
    }


    /**
     * 生成Model文件
     *
     * @param clist
     * @return
     */
    public String getCodeValidateColumn(List<SysCodeColumn> clist, boolean form_v_api) {
        if (!form_v_api) return "";
        StringBuffer sb = new StringBuffer();
        for (SysCodeColumn cc : clist) {
            String cc_name = cc.mod.getStr("cc_name");
            String f_vmsg = cc.mod.getStr("f_vmsg");
            if (cc.mod.getInt("f_vnull") == 1) {
                sb.append("        validateRequiredString(\"" + cc_name + "\", \"" + f_vmsg + "\");\n");
            }
            if (cc.mod.getInt("f_vemail") == 1) {
                sb.append("        validateRequiredString(\"" + cc_name + "\", \"" + f_vmsg + "\");\n");
            }
            if (cc.mod.getInt("f_vdate") == 1) {
                sb.append("        validateRequiredString(\"" + cc_name + "\", \"" + f_vmsg + "\");\n");
            }
            if (cc.mod.getInt("f_vnumber") == 1) {
                sb.append("        validateRequiredString(\"" + cc_name + "\", \"" + f_vmsg + "\");\n");
            }
        }
        return sb.toString();
    }

    /**
     * 编辑显示列表
     *
     * @param cid
     * @return
     */
    public List<SysCodeColumn> getCodeModifyColumn(int cid) {
        List<SysCodeColumn> cl = SysCodeColumn.dao.find("select * from sys_code_column where c_id=? and is_edit=1 order by sindex", cid);
        return cl;
    }

    /**
     * 生成Model文件
     *
     * @param code
     * @return
     */
    public String getCodeModifyColumnCode(SysCode code, List<SysCodeColumn> cl) {
        List<SysCodeColumn> clist = getModifyList(cl);
        int c_id = code.mod.getInt("c_id");
        String modelsname = code.mod.getStr("model_sname");
        String columns = "";
        String data = new StringBuffer(readDemoFile("ModifyDemoColumn.html")).toString();
        for (SysCodeColumn cc : clist) {
            int is_key = cc.mod.getInt("is_key", 0);
            String cc_name = cc.mod.getStr("cc_name");
            String cctitle = cc.mod.getStr("cc_title");
            String cc_type = cc.mod.getStr("cc_type");
            if (is_key == 0) {
                if ("|int|long|".indexOf("|" + cc_type + "|") > -1) {
                    columns += ".set(\"" + cc_name + "\", data.getInt(\"" + cc_name + "\"))\n";
                } else if ("|date|datetime|timestamp|".indexOf("|" + cc_type + "|") > -1) {
                    columns += ".set(\"" + cc_name + "\", data.getDate(\"" + cc_name + "\"))\n";
                } else {
                    columns += ".set(\"" + cc_name + "\", data.getStr(\"" + cc_name + "\"))\n";
                }
            }
        }
        return columns;
    }

    public List<SysCodeColumn> getCodeColumn(SysCode code) {
        int c_id = code.mod.getInt("c_id");
        List<SysCodeColumn> cl = SysCodeColumn.dao.find("select * from sys_code_column where c_id=? order by sindex", c_id);
        return cl;
    }

    /**
     * 找出需要搜索的字段
     *
     * @param columnlist
     * @return
     */
    public List<SysCodeColumn> getSearchList(List<SysCodeColumn> columnlist) {
        List<SysCodeColumn> slist = new ArrayList();
        for (SysCodeColumn cl : columnlist) {
            if (cl.mod.getInt("t_search", 0) == 1 || cl.mod.getInt("t_searchs", 0) == 1) slist.add(cl);
        }
        return slist;
    }


    /**
     * 找出需要搜索的字段
     *
     * @param columnlist
     * @return
     */
    public List<SysCodeColumn> getModifyList(List<SysCodeColumn> columnlist) {
        List<SysCodeColumn> slist = new ArrayList();
        for (SysCodeColumn cl : columnlist) {
            if (cl.mod.getInt("f_show", 0) == 1 || cl.mod.getInt("f_hidden", 0) == 1) {
                if (cl.mod.getInt("f_auto", 0) == 0) slist.add(cl);
            }
        }
        return slist;
    }

    /**
     * 读取模板文件
     *
     * @param filename
     * @return
     */
    public StringBuffer readDemoFile(String filename) {
        try {
            String paths = ConfigUtil.getWebInfoPath() + "/resource/demo/" + filename;
            return new FileControl(new File(paths)).readFileBuffer();
        } catch (Exception e) {
            return new StringBuffer("读取文件失败" + e.getMessage());
        }
    }

    /**
     * 填写默认提示信息
     *
     * @param id
     * @param field
     */
    public void initColumnVmsg(int id, String field) {
        SysCodeColumn column = SysCodeColumn.dao.findById(id);
        if (column != null) {
            String cc_title = column.mod.getStr("cc_title");
            String f_vmsg = column.mod.getStr("f_vmsg", "");
            if ("f_vnull".equals(field) && f_vmsg.length() == 0) {
                column.set("f_vmsg", cc_title + "不能为空");
            } else if ("f_vnumber".equals(field) && f_vmsg.length() == 0) {
                column.set("f_vmsg", cc_title + "必须是数字");
            } else if ("f_vemail".equals(field) && f_vmsg.length() == 0) {
                column.set("f_vmsg", cc_title + "格式不正确");
            } else if ("f_vdate".equals(field) && f_vmsg.length() == 0) {
                column.set("f_vmsg", cc_title + "格式不正确");
            } else if ("f_vexit".equals(field) && f_vmsg.length() == 0) {
                column.set("f_vmsg", cc_title + "已存在");
            }
            column.update();
        }
    }

}
